package com.hzgj.soa.protocol.pb.handler;

import com.hzgj.bcl.soa.net.Encoder;
import com.hzgj.bcl.soa.rpc.message.Message;
import com.hzgj.bcl.soa.util.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.StandardCharsets;

import static com.hzgj.soa.protocol.pb.handler.PbConstants.CRLF;
import static com.hzgj.soa.protocol.pb.handler.PbConstants.PB_PROTOCOL;

public class PbEncoder extends Encoder {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {

        Integer type = (Integer) msg.getHeader(Constants.MESSAGE_TYPE);
        boolean request = (type == null || type == Message.REQ);

        // "magic " + [length] + "\r\n" + [data]
        if (request) {
            byte[] bytes = (byte[]) msg.getPayload();
            out.writeInt(PbConstants.REQUEST_MAGIC);
            out.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
            out.writeBytes(CRLF);
            out.writeBytes(bytes);
        } else {
            byte[] bytes = (byte[]) msg.getPayload();
            out.writeInt(PbConstants.RESPONSE_MAGIC);
            out.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
            out.writeBytes(CRLF);
            out.writeBytes(bytes);
        }
    }

    @Override
    public String getName() {
        return PB_PROTOCOL;
    }
}